package com.ruoyi.operation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.utils.BeanCopyUtils;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.operation.domain.bo.TGentaskBo;
import com.ruoyi.operation.domain.vo.TGenTaskListResultVo;
import com.ruoyi.operation.domain.vo.TGentaskVo;
import com.ruoyi.operation.service.ITGentaskService;
import com.ruoyi.system.api.RemoteDictService;
import com.ruoyi.system.api.RemoteTBsCalendarService;
import com.ruoyi.system.api.domain.TBsCalendar;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import com.ruoyi.operation.domain.bo.TGentaskListBo;
import com.ruoyi.operation.domain.vo.TGentaskListVo;
import com.ruoyi.operation.domain.TGentaskList;
import com.ruoyi.operation.mapper.TGentaskListMapper;
import com.ruoyi.operation.service.ITGentaskListService;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生成的任务流水Service业务层处理
 *
 * @author chq
 * @date 2025-06-13
 */
@RequiredArgsConstructor
@Service
public class TGentaskListServiceImpl implements ITGentaskListService {

    private final TGentaskListMapper baseMapper;

    private final ITGentaskService gentaskService;

    @DubboReference
    private RemoteTBsCalendarService remoteTBsCalendarService;

    /**
     * 查询生成的任务流水
     */
    @Override
    public TGentaskListVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public TGentaskListVo queryByGentaskidAndTaskdate(String gentaskid, String taskdate) {
        QueryWrapper<TGentaskList> qw = new QueryWrapper<>();
        qw.lambda().eq(TGentaskList::getGentaskid, gentaskid)
            .eq(TGentaskList::getTaskdate, taskdate);
        return baseMapper.selectVoOne(qw);
    }

    /**
     * 查询生成的任务流水列表
     */
    @Override
    public TableDataInfo<TGentaskListVo> queryPageList(TGentaskListBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TGentaskList> lqw = buildQueryWrapper(bo);
        Page<TGentaskListVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询生成的任务流水列表
     */
    @Override
    public List<TGentaskListVo> queryList(TGentaskListBo bo) {
        LambdaQueryWrapper<TGentaskList> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TGentaskList> buildQueryWrapper(TGentaskListBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TGentaskList> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getGentaskid()), TGentaskList::getGentaskid, bo.getGentaskid());
        lqw.eq(StringUtils.isNotBlank(bo.getTaskdate()), TGentaskList::getTaskdate, bo.getTaskdate());
        lqw.eq(StringUtils.isNotBlank(bo.getTaskstatus()), TGentaskList::getTaskstatus, bo.getTaskstatus());
        lqw.eq(StringUtils.isNotBlank(bo.getResultvalue()), TGentaskList::getResultvalue, bo.getResultvalue());
        return lqw;
    }

    /**
     * 新增生成的任务流水
     */
    @Override
    public Boolean insertByBo(TGentaskListBo bo) {
        TGentaskList add = BeanUtil.toBean(bo, TGentaskList.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改生成的任务流水
     */
    @Override
    public Boolean updateByBo(TGentaskListBo bo) {
        TGentaskList update = BeanUtil.toBean(bo, TGentaskList.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TGentaskList entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除生成的任务流水
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<TGentaskListVo> upsertDaytask(TGentaskListBo bo) {
        if (StringUtils.isEmpty(bo.getTaskdate())) {
            bo.setTaskdate(DateUtils.parseDateToStr("yyyyMMdd", new Date()));
        }
        TGentaskListVo tGentaskListVo = queryByGentaskidAndTaskdate(bo.getGentaskid(), bo.getTaskdate());
        TGentaskList tGentaskList = new TGentaskList();
        TGentaskList copy = BeanCopyUtils.copy(bo, tGentaskList);
        if (tGentaskListVo != null) {
            copy.setId(tGentaskListVo.getId());
        }
        baseMapper.insertOrUpdate(tGentaskList);
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageSize(800);
        return queryPageList(bo, pageQuery);
    }

    @Override
    public TableDataInfo<TGentaskListVo> initDaytask(String dateEight) {    //注意可重复执行
        TBsCalendar tBsCalendar = remoteTBsCalendarService.selectTBsCalendarByNatureday(dateEight);
        //删除当日全量数据首先
        TGentaskListBo delBo = new TGentaskListBo();
        delBo.setTaskdate(dateEight);
        List<TGentaskListVo> tGentaskListVos = queryList(delBo);
        tGentaskListVos.forEach(e -> baseMapper.deleteById(e.getId()));
        //将维护D日的情况，无条件增加进去
        TGentaskBo bo = new TGentaskBo();//用作查询条件
        bo.setFlag("1");
        bo.setPeriod("D");
        List<TGentaskVo> tGentaskVos = Optional.ofNullable(gentaskService.queryList(bo)).orElse(new ArrayList<TGentaskVo>());
        //将维护dateRight的情况,无条件增加进去
        bo.setPeriod(dateEight);
        tGentaskVos.addAll(gentaskService.queryList(bo));
        //将维护T的情况，如果是工作日，则维护进去
        if ("0".equals(tBsCalendar.getDealflag())) {    //0工作日
            bo.setPeriod("T");
            tGentaskVos.addAll(gentaskService.queryList(bo));
        }
        //将维护C既是香港工作日又是内地工作日情况，如果是，则维护进去
        if ("0".equals(tBsCalendar.getHkdealflag()) && "0".equals(tBsCalendar.getDealflag())) {  //0香港工作日
            bo.setPeriod("C");
            tGentaskVos.addAll(gentaskService.queryList(bo));
        }
        //其他枚举类型，是后续再新增

        //将结果轮询后插入到List表
        tGentaskVos.stream().map(tGentask -> {
            TGentaskListBo tGentaskListBo = new TGentaskListBo();
            tGentaskListBo.setGentaskid(tGentask.getId());
            tGentaskListBo.setTaskdate(dateEight);
            tGentaskListBo.setTaskstatus("0");
            return BeanCopyUtils.copy(tGentaskListBo, TGentaskList.class);
        }).forEach(baseMapper::insert);


        TGentaskListBo tGentaskListBo = new TGentaskListBo();
        tGentaskListBo.setTaskdate(dateEight);
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageSize(800);
        return queryPageList(tGentaskListBo, pageQuery);
    }
}
